const crypto = require('crypto');
const superagent = require('superagent');
const chalk = require('chalk');
const {
    wConfig
} = require('../config')

function sha1(str) {
    let shasum = crypto.createHash("sha1");
    return shasum.update(str, 'utf-8').digest("hex");
}
const {
    WECHATAPI, wechatAPIS
} = require('../tools/wechatApi');
module.exports = async ctx => {
    try {
        let ticket = await wechatAPIS.getTicket();
        let nonceStr = Math.floor(Math.random() * 10000).toString();
        let timestamp = Math.floor(+new Date() / 1000);
        let url = ctx.req.headers['referer'];
        let str = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
        let signature = sha1(str);
        let data = {
            appId: wConfig.appID,
            nonceStr,
            timestamp,
            signature,
            url
        };
        ctx.state.data = {
            data,
            code: '001'
        }
    } catch (error) {
        ctx.state.data = {
            code: '002'
        }
    }
};